#!/usr/bin/php
<?php


$force = false;
$infile_name = null;
$outfile_name = null;

$infile = STDIN;
$outfile = STDOUT;

if($argc > 1)
{	
	for($nargs = count($argv), $i = 1; $i < $nargs; ++$i)
	{
		$last_arg = $nargs - 1;
		switch($argv[$i])
		{
			case '--force':
				$force = true;
				break;

			case '--in':
				if($i == $last_arg)
					die("--in: option requires an argument\n");
				$infile_name = $argv[++$i];
				break;

			case '--out':
				if($i == $last_arg)
					die("--out: option requires an argument\n");
				$outfile_name = $argv[++$i];
				break;
		}
	}

	if($infile_name && $outfile_name && is_readable($infile_name)
		&& is_writable($outfile_name) && !$force)
	{
		$in_stat = stat($infile_name);
		$out_stat = stat($outfile_name);

		if($in_stat['mtime'] < $out_stat['mtime'])
		{
			fwrite(STDERR, "File is up to date\n");
			return;
		}
	}

	if($infile_name)
	{
		$infile = fopen($infile_name, 'r');
		if(!$infile)
			die("Cannot open '$infile_name' for reading\n");
	}

	if($outfile_name)
	{
		$outfile = fopen($outfile_name, 'w');
		if(!$outfile)
			die("Cannot open '$outfile_name' for writing\n");
	}
}

$date = strftime("%Y-%m-%d %H:%M:%S%Z");
$user = get_current_user();

$output = <<<EOHEADER
#ifndef DATABASE_EXCEPTIONS_H
#define DATABASE_EXCEPTIONS_H
/*
	Database exceptions

	Generated on $date by $user
*/

#include "exceptions_base.h"


namespace Database
{
EOHEADER;

for($line = 1; !feof($infile); ++$line)
{
	$ex = fgetcsv($infile);
	$str = $ex ? trim(join(',', $ex)) : '';

	if(!strlen($str) || ($str[0] == ';'))
		continue;

	if(count($ex) != 5)
	{
		fprintf(STDERR, "line: " . join(",", $ex) ."\n");
		fprintf(STDERR, "count(ex): " . count($ex) . "\n");
		fprintf(STDERR, "Syntax error on line $line; skipping\n");
		continue;
	}

	$output .= <<<EOEXCEPTION


class {$ex[0]} : public {$ex[1]}
{
public:
	{$ex[0]}() : {$ex[1]}({$ex[3]}, "{$ex[4]}") { };
};

EOEXCEPTION;
}

fclose($infile);

$output .= <<<EOFOOTER

}	// namespace Database

#endif

EOFOOTER;

fwrite($outfile, $output);

